<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h2>用户登录</h2>
        <p class="login-subtitle">请输入您的账号信息以继续</p>
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="rules" class="login-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" @keyup.enter="handleLogin" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" @keyup.enter="handleLogin" />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-container">
            <el-input v-model="loginForm.captcha" placeholder="请输入验证码" class="captcha-input" @keyup.enter="handleLogin" />
            <div class="captcha-display" @click="generateCaptcha" title="点击刷新验证码">
              <span class="captcha-text">{{ captchaData.num1 }} {{ captchaData.operator }} {{ captchaData.num2 }} = ?</span>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          <el-link type="primary" :underline="false" @click="handleRegister">立即注册</el-link>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-button" @click="handleLogin" :loading="loading">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { authService } from '../services/authService'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../store'

const router = useRouter()

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  rememberMe: false
})

// 验证码数据
const captchaData = reactive({
  num1: 0,
  num2: 0,
  operator: '+',
  result: 0
})

// 表单引用
const loginFormRef = ref(null)

// 加载状态
const loading = ref(false)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, 
      message: '用户名只能包含字母、数字、下划线和中文', 
      trigger: 'blur' 
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/, 
      message: '密码只能包含字母、数字和常见特殊字符', 
      trigger: 'blur' 
    }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (parseInt(value) !== captchaData.result) {
          // 验证码错误时自动刷新
          generateCaptcha()
          callback(new Error('验证码错误，已自动刷新'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 生成验证码
const generateCaptcha = () => {
  // 生成1-9的随机数
  captchaData.num1 = Math.floor(Math.random() * 9) + 1
  captchaData.num2 = Math.floor(Math.random() * 9) + 1
  
  // 随机选择运算符
  const operators = ['+', '-']
  captchaData.operator = operators[Math.floor(Math.random() * operators.length)]
  
  // 计算结果
  switch (captchaData.operator) {
    case '+':
      captchaData.result = captchaData.num1 + captchaData.num2
      break
    case '-':
      // 确保结果为正数
      if (captchaData.num1 < captchaData.num2) {
        [captchaData.num1, captchaData.num2] = [captchaData.num2, captchaData.num1]
      }
      captchaData.result = captchaData.num1 - captchaData.num2
      break
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) {
    ElMessage.error('表单未初始化')
    return
  }
  
  try {
    // 表单验证
    await loginFormRef.value.validate()
    
    loading.value = true
    // 调用登录接口（不包含验证码）
    const loginData = {
      username: loginForm.username,
      password: loginForm.password
    }
    const result = await authService.login(loginData)
    
    // 登录成功后清空验证码
    loginForm.captcha = ''
    
    if (result && result.token) {
      // 保存登录结果到store
      const userStore = useUserStore()
      userStore.saveLoginResult(result)
      
      // 如果选择了记住我，保存用户名
      if (loginForm.rememberMe) {
        localStorage.setItem('username', loginForm.username)
      } else {
        localStorage.removeItem('username')
      }
      
      ElMessage.success('登录成功')
      
      // 检查是否有重定向路径
      const redirect = router.currentRoute.value.query.redirect
      if (redirect) {
        // 跳转到原始请求页面
        router.push(redirect)
      } else {
        // 检查是否有待提交的订单数据
        const pendingOrderData = localStorage.getItem('pendingOrderData')
        if (pendingOrderData) {
          // 清除待提交的订单数据
          localStorage.removeItem('pendingOrderData')
          // 跳转到订单确认页面
          router.push('/order/confirm')
        } else {
          // 登录成功后跳转到首页
          router.push('/')
        }
      }
    } else {
      ElMessage.error('请仔细检查登录信息!^_^')
    }
  } catch (error) {
    console.error('登录失败:', error)
    
    // 优化错误提示，根据错误类型给出更友好的提示
    let errorMessage = '登录失败，请检查用户名和密码'
    
    if (error.customMessage) {
      // 使用API层提供的详细错误信息
      errorMessage = error.customMessage
    } else if (error.statusCode) {
      // 根据HTTP状态码给出具体提示
      switch (error.statusCode) {
        case 400:
          errorMessage = '用户名或密码错误，请重新输入'
          break
        case 401:
          errorMessage = '用户名或密码不正确'
          break
        case 403:
          errorMessage = '账户被锁定或禁用，请联系客服'
          break
        case 404:
          errorMessage = '用户不存在，请检查用户名'
          break
        case 500:
          errorMessage = '服务器繁忙，请稍后再试'
          break
        default:
          errorMessage = '登录失败，请检查网络连接'
      }
    } else if (error.message) {
      errorMessage = error.message
    }
    
    // 使用Element Plus的Message组件显示错误信息
    ElMessage.error({
      message: errorMessage,
      duration: 4000, // 显示4秒
      showClose: true, // 显示关闭按钮
      grouping: true // 相同消息分组
    })
    
    // 登录失败后刷新验证码
    generateCaptcha()
    // 清空验证码输入
    loginForm.captcha = ''
  } finally {
    loading.value = false
  }
}

// 处理注册
const handleRegister = () => {
  router.push('/register')
}

// 页面加载时，如果有记住的用户名，自动填充
const initForm = () => {
  const savedUsername = localStorage.getItem('username')
  if (savedUsername) {
    loginForm.username = savedUsername
    loginForm.rememberMe = true
  }
}

// 初始化表单
initForm()

// 初始化验证码
generateCaptcha()
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
}

.login-subtitle {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.login-form {
  padding: 0 10px;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-display {
  background: linear-gradient(45deg, #f0f8ff, #e6f7ff);
  border: 1px solid #1890ff;
  border-radius: 6px;
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 80px;
  text-align: center;
}

.captcha-display:hover {
  background: linear-gradient(45deg, #e6f7ff, #bae7ff);
  border-color: #40a9ff;
  transform: translateY(-1px);
}

.captcha-text {
  font-size: 16px;
  font-weight: 600;
  color: #1890ff;
  user-select: none;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 6px;
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: linear-gradient(135deg, #096dd9 0%, #0050b3 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.login-button:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    margin: 10px;
  }
  
  .login-header h2 {
    font-size: 24px;
  }
}

/* 错误提示样式优化 */
:deep(.el-form-item__error) {
  font-size: 12px;
  padding-top: 4px;
}

:deep(.el-message) {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-message--error) {
  background: linear-gradient(135deg, #ff4d4f 0%, #cf1322 100%);
  border: none;
  color: white;
}

:deep(.el-message--success) {
  background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  border: none;
  color: white;
}
</style>